<template>
	<view>
		<navbar title="下载页" left="arrow-left" v-if="client!='web'">
			<view @click="shareUrl()" v-if="client!='web'">
				<u-icon name="share" color="#373737" size="30" style="margin-right: 3px;"></u-icon>
			</view>
		</navbar>
		<!-- 密码页 -->
		<u-modal :show="passwordmode" :showConfirmButton="false">
			<view>
				<h3>密码验证</h3>
				<u--input style="width: 250px;margin: 10px 0;" placeholder="请输入密码进行访问" border="surround"
					v-model="password"></u--input>
				<button type="primary" @click="verify">确认</button>
			</view>
		</u-modal>
		<ad-rewarded-video ref="adRewardedVideo" adpid="1481353487" :loadnext="true" v-slot:default="{loading, error}"
			@load="onadload" @close="onadclose" @error="error">
		</ad-rewarded-video>
		<unicloud-db getone :disabled="isLoading" :loading="isLoading" @load="handle" loadtime="manual" ref="udb"
			style="background-color: white;" v-slot:default="{data, loading, error,options }" collection="item"
			:where="where" :field="field">
			<file_jingdian ref="filejd" v-if="openup=='file_jingdian'" :data="data" :page="page" />
			<moren @down="down" v-if="openup=='moren'" :data="data" />
			<document v-if="openup=='document'" :data="data" />
			<apk_moren @down="down" v-if="openup=='apk_moren'" :data="data" />
			<apk_jingdian @down="down" v-if="openup=='apk_jingdian'" :data="data" />
			<apk_ios @down="down" v-if="openup=='apk_ios'" :data="data" />
			<apk_md @down="down" v-if="openup=='apk_md'" :data="data" />
			<apk_tiankong @down="down" v-if="openup=='apk_tiankong'" :data="data" />
			<apk_black @down="down" v-if="openup=='apk_black'" :data="data" />
			<apk_user_728 @down="down" v-if="openup=='apk_user_728'" :data="data" />
			<apk_user_729 @down="down" v-if="openup=='apk_user_729'" :data="data" />
			<apk_jianyue @down="down" v-if="openup=='apk_jianyue'" :data="data" />
		</unicloud-db>
		<u-loading-page fontSize="16" bgColor="#fff" iconSize="30" loadingText="数据加载中" :loading="success"
			loading-mode="semicircle"></u-loading-page>
	</view>
</template>

<script>
	const db = uniCloud.database();
	import store from '@/store/index.js';
	export default {
		data() {
			return {
				field: "title,content,user_id,type,time,size,weight,icon,package,version,image,down,ip,duration,openup,top,last_time,password_mode",
				openup: null,
				passwordmode: false,
				itemdata: null,
				page: 1,
				where: "_id==''",
				id: null,
				password: null,
				isLoading: false,
				aderror: false,
				downshow: false,
				success: true
			};
		},
		methods: {
			async shareUrl() {
				const res = await db.collection("item").where({
					_id: this.id
				}).get({
					getOne: true
				})
				var icon = this.geticon(res.result.data.type, res.result.data.icon)
				uni.share({
					provider: "qq",
					type: 0,
					title: res.result.data.title,
					href: "https://x2.ink/pages/share/share?id=" + this.id,
					imageUrl: icon,
					summary: "我在小二云盘发现了一款超级好玩的文件！赶紧来看看吧！"
				});
			},
			handle(data) {
				console.log("加载数据", data);
				this.success = false
				this.itemdata = data
				this.openup = data.openup
				this.passwordmode = data.password_mode
				data.size = this.gsbytes(data.size)
			},
			async verify() {
				const res = await db.collection("item").where({
					_id: this.id,
					password: this.password
				}).count()
				if (res.result.total > 0) {
					this.message('验证成功')
					this.passwordmode = false
				} else {
					this.message('密码错误', 'error')
				}
			},
			count(id, type) {
				if (id == null) {
					return null
				}
				uniCloud.callFunction({
					name: 'ip_down',
					data: {
						id: id,
						type: type
					}
				});
			},
			async down(val) {
				var that = this
				const res = await db.collection("item").where({
					_id: val.id
				}).field("money").get()
				if (res.result.data[0].money > 0) {
					if (this.client != 'app') {
						uni.showModal({
							title: '温馨提示',
							content: `此文件为付费文件，请下载小二云盘App进行购买，或者联系文件分享者获取！`,
							success() {
								window.location.href = "http://www.x2.ink"
							}
						});
						return null
					}
					const pd = await db.collection("order").where({
						item_id: val.id,
						user_id: this.user_id
					}).count()
					if (pd.result.total > 0) {
						this.download(val.id)
						return null
					}
					uni.showModal({
						title: '温馨提示',
						content: `你需要花费${res.result.data[0].money}元购买此文件`,
						success: async function(req) {
							if (req.confirm) {
								uniCloud.callFunction({
									name: 'getorderinfo',
									data: {
										subject: `用户${that.user_id}购买文件${that.itemdata.title}`,
										outTradeNo: that.randomString(false, 32),
										totalFee: res.result.data[0].money * 100
									},
									success(req1) {
										uni.requestPayment({
											provider: 'alipay',
											orderInfo: req1.result.OrderInfo,
											success: async function(res1) {
												that.buySuccess(res.result.data[0]
													.money, res1.tradeno)
											}
										});
									}
								})
							}
						}
					});
				} else {
					if (this.itemdata.password_mode) {
						if (this.passwordmode) {
							this.message("请输入密码", 'error')
							return
						}
					}
					if (this.aderror || store.state.userInfo.vip > new Date().getTime()) {
						this.download(this.id)
						return
					}
					if (this.isLoading) {
						return
					}
					if (this.client == 'app') {
						uni.showModal({
							title: '温馨提示',
							content: '检测到你当前为非会员用户，下载文件需要观看激励视频获得下载资格！',
							cancelText: "观看广告",
							confirmText: "充值会员",
							success: function(res) {
								if (res.confirm) {
									that.goPage("pay")
								} else if (res.cancel) {
									that.$refs.adRewardedVideo.show();
								}
							}
						});
					} else {
						this.count(this.id, 'down')
						const res = await db.collection("item").where({
							_id: this.id
						}).field("url").get()
						this.downloadUrl(res.result.data[0].url)
					}
				}
			},
			async buySuccess(money, no) {
				const res = await db.collection("order").add({
					user_id: this.user_id,
					item_id: this.id,
					create_time: new Date(),
					money: Number(money),
					alipay: no
				})
				await db.collection("money").add({
					buyuser: this.user_id,
					user_id: this.itemdata.user_id,
					money: Number(money),
					title: this.itemdata.title,
					time: new Date(),
					alipay: no
				})
				this.download(this.id)
			},
			error(e) {
				console.log("广告加载错误", e);
				this.aderror = true
			},
			onadload(e) {
				this.$nextTick(() => {
					this.$refs.udb.loadData({
						clear: true
					})
				})
				console.log(e);
			},
			async onadclose(e) {
				if (e.detail.isEnded) {
					this.download(this.id)
				} else {
					this.message('未看完广告', "error")
				}
			},
			async send(title, content) {
				const res = await db.collection("message").add({
					from: this.itemdata.user_id,
					msg_type: "filedetail",
					msg_id: this.id,
					title: title,
					content: content,
					to: this.user_id,
					time: new Date()
				})
			},
			downloadUrl(url, title, icon, id) {
				uni.showLoading({
					title: '地址解析中'
				});
				var that = this
				this.getUrl(url, (res) => {
					uni.hideLoading()
					if (res.data.code == 200) {
						let url = res.data.downUrl
						let suffix = res.data.name.substring(res.data.name.lastIndexOf('.') + 1)
						if (this.client == "web") {
							window.location.href = url
						} else {
							store.commit('setDownload', {
								name: `${title}.${suffix}`,
								icon: icon,
								url: url,
								id: id
							})
							this.goPage('download')
						}
					} else {
						this.openUrl(url)
					}
				})
			},
			async download(id) {
				var that = this
				this.count(id, 'down')
				const res = await db.collection("item").where({
					_id: id
				}).field("url").get()
				var content =
					`文件名称:${this.itemdata.title}\n下载地址:<a style='color:blue' href='${res.result.data[0].url}'>下载链接</a>`
				this.send("文件购买成功！", content)
				uni.showModal({
					title: '购买成功',
					content: '恭喜你！购买文件成功！文件下载直链已经发放到你的邮箱，请去邮箱查看，点击确定可以进行本地下载',
					success: function(req) {
						if (req.confirm) {
							var suffix = res.result.data[0].url.slice(res.result.data[0].url.lastIndexOf(
								'.') + 1)
							that.downloadUrl(res.result.data[0].url, that.itemdata.title, that.itemdata
								.icon, that.itemdata._id)
						}
					}
				});
			}
		},
		onReachBottom() {
			if (this.openup == 'file_jingdian') {
				++this.page
			}
		},
		async onLoad(op) {
			if (op.id == null) {
				uni.redirectTo({
					url: '/pages/file404/file404'
				});
				return
			} else {
				this.id = op.id
				const res = await db.collection("item").where({
					_id: op.id
				}).count()
				console.log("有没有这个数据", res);
				if (res.result.total == 0) {
					uni.redirectTo({
						url: '/pages/file404/file404'
					});
				} else {
					this.where = `_id=='${op.id}'`
					this.$nextTick(() => {
						this.$refs.udb.loadData({
							clear: true
						})
					})
				}
			}
			this.count(op.id, 'ip')
		}
	}
</script>

<style lang="less">
	body {
		background-color: white;
	}
</style>